<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <SearchForm ref="searchForm" :show-search="showSearch" @query="handleQuery" />

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download" size="mini" :loading="exportLoading"
          @click="handleExport" v-hasPermi="['logistics:shipment:export']">
          导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-refresh" size="mini" @click="handleRefresh">
          刷新
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 运单列表表格 -->
    <ShipmentTable :shipment-list="shipmentList" :loading="loading" @selection-change="handleSelectionChange"
      @detail="handleDetail" @sort-change="handleSortChange" />

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 轨迹详情抽屉 -->
    <TrackingDrawer :visible="trackingVisible" :shipment-info="currentShipment" @close="handleTrackingClose" />
  </div>
</template>

<script>
import SearchForm from './components/SearchForm'
import ShipmentTable from './components/ShipmentTable'
import TrackingDrawer from './components/TrackingDrawer'
import { getShipmentComprehensive, exportShipment } from './api/comprehensive'
import { parseTime } from '@/utils/ruoyi'

export default {
  name: 'ShipmentStatus',
  components: {
    SearchForm,
    ShipmentTable,
    TrackingDrawer
  },
  data () {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 运单表格数据
      shipmentList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        billNo: undefined,
        billStatus: undefined,
        senderName: undefined,
        receiverName: undefined,
        beginTime: undefined,
        endTime: undefined,
        sortField: undefined,
        sortOrder: undefined
      },
      // 轨迹抽屉显示状态
      trackingVisible: false,
      // 当前选中的运单
      currentShipment: null
    }
  },
  created () {
    this.getList()
  },
  methods: {
    /** 查询运单列表 */
    async getList () {
      this.loading = true
      try {
        // 准备查询参数，将排序条件转换为字符串
        const params = { ...this.queryParams }
        if (params.sortField && params.sortOrder) {
          params.sortColumnsStr = `${params.sortField}:${params.sortOrder}`
          delete params.sortField
          delete params.sortOrder
        }

        console.log('发送查询参数:', params)

        const response = await getShipmentComprehensive(params)

        // 处理后端返回的数据结构
        if (response && response.rows) {
          this.shipmentList = response.rows
          this.total = response.total
        } else if (response && response.data) {
          // 兼容可能的其他数据结构
          this.shipmentList = response.data.rows || response.data
          this.total = response.data.total || response.data.length
        } else {
          this.shipmentList = []
          this.total = 0
        }

      } catch (error) {
        console.error('查询运单列表失败:', error)
        this.$modal.msgError('查询运单列表失败')
        this.shipmentList = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    /** 搜索按钮操作 */
    handleQuery (params) {
      this.queryParams = {
        ...this.queryParams,
        ...params,
        pageNum: 1
      }
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery () {
      this.$refs.searchForm.resetQuery()
    },

    /** 多选框选中数据 */
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 详情按钮操作 */
    handleDetail (row) {
      this.currentShipment = row
      this.trackingVisible = true
    },

    /** 排序变化 */
    handleSortChange (column) {
      console.log('排序变化，列信息:', column)

      if (column.order) {
        // 设置排序字段和方向
        this.queryParams.sortField = column.prop
        this.queryParams.sortOrder = column.order === 'ascending' ? 'asc' : 'desc'
        console.log(`设置排序：字段=${column.prop}, 方向=${this.queryParams.sortOrder}`)
      } else {
        // 清除排序
        this.queryParams.sortField = undefined
        this.queryParams.sortOrder = undefined
        console.log('清除排序')
      }

      // 重置页码并重新查询
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 导出按钮操作 */
    handleExport () {
      // 准备导出参数
      const exportParams = {
        ...this.queryParams,
        pageNum: undefined,  // 导出时不需要分页参数
        pageSize: undefined
      }

      // 处理排序参数
      if (exportParams.sortField && exportParams.sortOrder) {
        exportParams.sortColumnsStr = `${exportParams.sortField}:${exportParams.sortOrder}`
        delete exportParams.sortField
        delete exportParams.sortOrder
      }

      // 如果有选中的行，则导出选中的数据
      if (this.ids && this.ids.length > 0) {
        exportParams.ids = this.ids
        this.$modal.confirm(`是否确认导出选中的${this.ids.length}条运单数据?`).then(() => {
          this.performExport(exportParams, `选中运单数据(${this.ids.length}条)`)
        }).catch(() => { })
      } else {
        // 没有选中数据，导出全部或过滤后的数据
        const hasFilters = this.queryParams.billNo || this.queryParams.billStatus ||
          this.queryParams.senderName || this.queryParams.receiverName ||
          this.queryParams.beginTime || this.queryParams.endTime ||
          this.queryParams.sortField

        let confirmMsg = '是否确认导出所有运单数据?'
        let description = '全部运单数据'

        if (hasFilters) {
          confirmMsg = '是否确认导出当前查询条件下的所有运单数据?'
          description = '筛选条件运单数据'
        }

        this.$modal.confirm(confirmMsg).then(() => {
          this.performExport(exportParams, description)
        }).catch(() => { })
      }
    },

    /** 执行导出操作 */
    performExport (exportParams, description) {
      this.exportLoading = true
      console.log('导出参数:', exportParams)

      exportShipment(exportParams).then(response => {
        // 检查响应数据
        if (!response) {
          throw new Error('导出响应为空')
        }

        const filename = `${description}_${this.parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`
        console.log('准备下载文件:', filename)

        // 使用下载插件处理Excel文件
        this.$download.excel(response, filename)
      }).catch(error => {
        console.error('导出失败:', error)
        let errorMsg = '导出失败'

        if (error.response) {
          // 服务器响应错误
          errorMsg += `: ${error.response.status} ${error.response.statusText}`
        } else if (error.message) {
          // 其他错误
          errorMsg += `: ${error.message}`
        }

        this.$modal.msgError(errorMsg)
      }).finally(() => {
        this.exportLoading = false
      })
    },

    /** 刷新按钮操作 */
    handleRefresh () {
      this.getList()
      this.$modal.msgSuccess('数据已刷新')
    },

    /** 关闭轨迹抽屉 */
    handleTrackingClose () {
      this.trackingVisible = false
      this.currentShipment = null
    },

    // 解析时间
    parseTime
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .mb8 {
    margin-bottom: 8px;
  }

  ::v-deep .el-card {
    border-radius: 4px;

    .el-card__header {
      padding: 18px 20px;
      border-bottom: 1px solid #ebeef5;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .card-title {
          font-size: 16px;
          font-weight: 500;
          color: #303133;
        }
      }
    }

    .el-card__body {
      padding: 20px;
    }
  }

  ::v-deep .el-table {
    .el-table__header-wrapper {
      th {
        background-color: #fafafa;
        color: #606266;
        font-weight: 500;
      }
    }

    .el-table__row {
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }

  ::v-deep .el-pagination {
    margin-top: 20px;
    text-align: right;
  }
}

// 响应式布局
@media (max-width: 768px) {
  .app-container {
    padding: 10px;

    ::v-deep .el-form--inline {
      .el-form-item {
        display: block;
        margin-right: 0;
        margin-bottom: 15px;

        .el-form-item__content {
          margin-left: 0 !important;
        }
      }
    }

    ::v-deep .el-table {
      font-size: 12px;

      .el-table__cell {
        padding: 6px 0;
      }
    }
  }
}
</style>
